# -*- coding: utf-8 -*-
# Created by huagnqiyin on 2016/9/6
import logging

from sanic import response

from _app import app

from appconfigsvr.web.salt_conf import get_app_config, get_app_global_template
from appconfigsvr.web.html_controller import html
from appconfigsvr.web.config_controller import bp as config_bp
from appconfigsvr.web.global_template import bp as global_bp
from appconfigsvr.web.env_conf import bp as env_bp
from appconfigsvr.auth.user import bp as user_bp
from appconfigsvr.auth.usergroup import bp as group_bp
from appconfigsvr.web.resource import bp as resource_bp
from appconfigsvr.web.salt_run import bp as salt_run_bp

from appconfigsvr.web.salt_run_config import bp as salt_run_config_bp

from settings import config

_logger = logging.getLogger()
_oplog = logging.getLogger("oplog")

import jwt

async def home(request):
    try:
        return response.redirect("/admin/index2.html")
    except Exception as e:
        _logger.exception("url %s exception %s" % (request.url, e))
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})


app.add_route(html, "<template_dir>/<html_file_name>.html$", methods=['GET'])

app.static('/asset', './templates')
app.add_route(home, "/", methods=['GET'])

app.add_route(get_app_config, "/config", methods=['GET'])
# http://localhost:19000/config?app_name=ratel&env=testenv&setting_key=settings

app.add_route(get_app_global_template, "/global_template", methods=['GET'])

app.blueprint(config_bp)
app.blueprint(global_bp)
app.blueprint(env_bp)
app.blueprint(user_bp)
app.blueprint(group_bp)
app.blueprint(resource_bp)
app.blueprint(salt_run_bp)

app.blueprint(salt_run_config_bp)

app.config.update(config)
if __name__ == '__main__':
    print("start main")
    app.run(host=config['HOST'],
            port=config['PORT'],
            debug=config['DEBUG'],
            workers=config['WORKER'],
            )
